# -*- coding: utf-8 -*-
import json
from django.conf import settings
from preprocessor.cp.preprocessor import CPEventPreprocessor
from preprocessor.dwc.preprocessor import DWCEventPreprocessor
from preprocessor.agent.preprocessor import AgentEventPreprocessor
from preprocessor.offline_calculation.preprocessor import OfflineCalculationEventPreprocessor
from preprocessor.mf_pay.preprocessor import MFPayEventPreprocessor
import time
from common.utils.maestro_exceptions import (
    MaestroException,
    ILLEGAL_PARAMETER
)

CP_TOPICS = settings.CP_INDEX
DWC_TOPICS = settings.DWC_INDEX
AGENT_TOPICS = settings.AGENT_INDEX
OFFLINE_CALCULATION_TOPICS = settings.OFFLINE_CALCULATION
MF_PAY_TOPICS = settings.MF_PAY_INDEX


class EventPreprocessorAdapter:
    def __init__(self, topic: str):
        handler_class = self.get_topic_handler_class(topic)
        self.handler = handler_class(topic)

    def handle(self, event_data):
        events = self.event_splitter(event_data)
        event_data_list = []
        for event in events:
            processed_event = self.handler.handle(event)
            if processed_event:
                event_data_list.append(processed_event)
        return event_data_list

    @staticmethod
    def event_splitter(event):
        event['_last_modified'] = int(time.time())
        if event['_event_id'] != 'fishing_bet':
            return [event]
        else:
            return EventPreprocessorAdapter.split_fish_event(event)

    @staticmethod
    def split_fish_event(event):
        fishes = []
        fish_types_str = event['fish_profit']
        fish_types_str = fish_types_str.replace("'", '"')
        fish_types = json.loads(fish_types_str)
        for k, v in fish_types.items():
            assert 'bet_amount' in v
            assert 'award_amount' in v
            event_data = event.copy()
            event_data.pop('fish_profit')
            event_data['_event_id'] = 'fishing_bet_item'
            event_data['_id'] = event_data['_id'] + ':' + str(event_data['_event_time']) + ':' + k
            event_data['fish_type'] = k
            event_data['bet_amount'] = v['bet_amount']
            event_data['award_amount'] = v['award_amount']
            fishes.append(event_data)
        return fishes

    @staticmethod
    def get_topic_handler_class(topic: str):
        if topic in CP_TOPICS:
            return CPEventPreprocessor
        elif topic in DWC_TOPICS:
            return DWCEventPreprocessor
        elif topic in AGENT_TOPICS:
            return AgentEventPreprocessor
        elif topic in OFFLINE_CALCULATION_TOPICS:
            return OfflineCalculationEventPreprocessor
        elif topic in MF_PAY_TOPICS:
            return MFPayEventPreprocessor
        else:
            raise MaestroException(ILLEGAL_PARAMETER)
